/*
 *    Copyright (c) 2018-2025, nart All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: nart
 */

package com.nai365.nart.product.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nai365.nart.common.core.util.R;
import com.nai365.nart.common.excel.annotation.ResponseExcel;
import com.nai365.nart.common.log.annotation.SysLog;
import com.nai365.nart.common.security.annotation.Inner;
import com.nai365.nart.product.entity.Brand;
import com.nai365.nart.product.entity.BrandFans;
import com.nai365.nart.product.service.BrandFansService;
import com.nai365.nart.product.service.BrandService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 俱乐部粉丝
 *
 * @author baogs
 * @date 2022-07-01 10:52:58
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/brandfans" )
@Api(value = "brandfans", tags = "俱乐部粉丝管理")
public class BrandFansController {

    private final BrandFansService brandFansService;
    private final BrandService brandService;

    /**
     * 分页查询
     * @param page 分页对象
     * @param brandFans 俱乐部粉丝
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page" )
    public R getBrandFansPage(Page page, BrandFans brandFans) {
        return R.ok(brandFansService.page(page, Wrappers.query(brandFans)));
    }
    /**
     * 分页查询
     * @param page 分页对象
     * @param brandFans 俱乐部粉丝
     * @return
     */
    @ApiOperation(value = "分页查询返回俱乐部信息", notes = "分页查询返回俱乐部信息")
    @GetMapping("/page_info" )
    public R getBrandFansPageInfo(Page page, BrandFans brandFans) {
		Long userId = brandFans.getUserId();
		LambdaQueryWrapper<BrandFans> brandFansLambdaQueryWrapper = new LambdaQueryWrapper<>();
		brandFansLambdaQueryWrapper.eq(BrandFans::getUserId,userId).eq(BrandFans::getFollow,true);
		Page page1 = brandFansService.page(page, brandFansLambdaQueryWrapper);
		List<BrandFans> records = page1.getRecords();
		if (records != null && records.size() > 0) {
			List<Long> collect = records.parallelStream().map(item -> item.getClubId()).collect(Collectors.toList());
			List<Brand> brands = brandService.listByIds(collect);
			Map<Long, Brand> collect1 = brands.parallelStream().map(item -> {
				Long brandId = item.getBrandId();
				long count = brandFansService.count(new LambdaQueryWrapper<BrandFans>().eq(BrandFans::getClubId, brandId).eq(BrandFans::getFollow, true));
				item.setFansCount(count);
				return item;
			}).collect(Collectors.toMap(Brand::getBrandId, Function.identity()));
			List<JSONObject> brandFans1 = records.parallelStream().map(item -> {
				Long clubId = item.getClubId();
				JSONObject fans = JSONUtil.parseObj(item);
				Brand brand = collect1.get(clubId);
				fans.putOpt("brand", brand);
				return fans;
			}).collect(Collectors.toList());

			page1.setRecords(brandFans1);
			return R.ok(page1);
		} else {
			return  R.failed("关注列表为空");
		}
    }


    /**
     * 通过id查询俱乐部粉丝
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}" )
    public R getById(@PathVariable("id" ) Long id) {
        return R.ok(brandFansService.getById(id));
    }

    /**
     * 新增俱乐部粉丝
     * @param brandFans 俱乐部粉丝
     * @return R
     */
    @ApiOperation(value = "新增俱乐部粉丝", notes = "新增俱乐部粉丝")
    @SysLog("新增俱乐部粉丝" )
    @PostMapping
    public R save(@RequestBody BrandFans brandFans) {
		BrandFans one = brandFansService.getOne(new LambdaQueryWrapper<BrandFans>().eq(BrandFans::getClubId, brandFans.getClubId())
				.eq(BrandFans::getUserId, brandFans.getUserId()));
		if (one != null){
			return R.failed("已关注过");
		} else {
			return R.ok(brandFansService.save(brandFans));
		}
    }

    /**
     * 新增俱乐部粉丝
     * @param brandFans 俱乐部粉丝
     * @return R
     */
    @ApiOperation(value = "粉丝添加和取消", notes = "粉丝添加和取消 传userId clubId follow值三个字段")
    @SysLog("新增俱乐部粉丝" )
    @PostMapping("/follow")
    public R follow(@RequestBody BrandFans brandFans) {
		BrandFans one = brandFansService.getOne(new LambdaQueryWrapper<BrandFans>().eq(BrandFans::getClubId, brandFans.getClubId())
				.eq(BrandFans::getUserId, brandFans.getUserId()),false);
		if (one != null){
			one.setUpdateTime(null);
			one.setFollow(brandFans.getFollow());
			brandFansService.updateById(one);
			String result = "";
			if (brandFans.getFollow()){
				result = "关注成功";
			}else{
				result = "取消成功";
			}
			return R.ok(result);
		} else {
			return R.ok(brandFansService.save(brandFans),"关注成功");
		}
    }

    /**
     * 修改俱乐部粉丝
     * @param brandFans 俱乐部粉丝
     * @return R
     */
    @ApiOperation(value = "修改俱乐部粉丝", notes = "修改俱乐部粉丝")
    @SysLog("修改俱乐部粉丝" )
    @PutMapping
    public R updateById(@RequestBody BrandFans brandFans) {
        return R.ok(brandFansService.updateById(brandFans));
    }

    /**
     * 通过id删除俱乐部粉丝
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除俱乐部粉丝", notes = "通过id删除俱乐部粉丝")
    @SysLog("通过id删除俱乐部粉丝" )
    @DeleteMapping("/{id}" )
    public R removeById(@PathVariable Long id) {
        return R.ok(brandFansService.removeById(id));
    }


    /**
     * 导出excel 表格
     * @param brandFans 查询条件
     * @return excel 文件流
     */
    @ResponseExcel
    @GetMapping("/export")
    public List<BrandFans> export(BrandFans brandFans) {
        return brandFansService.list(Wrappers.query(brandFans));
    }
}
